import { Menu } from 'antd';
import React, { useEffect, useMemo } from 'react';
import { connect } from 'umi';
import classNames from 'classnames';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import db from '@/utils/localstorage'
const SuperAdminRole = ['admin', 'enterprise_admin']
const SelectVenue = props => {
  const { dispatch, userVenueList, currentVenue } = props;
  useEffect(() => {
    dispatch({
      type: 'user/fetchVenueList',
      payload: {
        userId: db.get("user").userId
      }
    });
  }, [])

  const handleChange = ({ key }) => {
    if (key === '101') {
      //退出当前场馆
      db.save('venue',{ id: '101', name: '虚拟场馆' });
      //刷新页面
      window.location.reload();
      return;
    }
    dispatch({
      type: 'user/common',
      payload: {
        currentVenue: userVenueList[key]
      }
    });
    db.save('venue', userVenueList[key]);
    //刷新页面
    window.location.reload();
  }
  const VenueMenuList = useMemo(() => {
    let isSuperAdmin;
    const roles = db.get("roles");
    if (roles && Array.isArray(roles)) {
      isSuperAdmin = roles.find(item => SuperAdminRole.includes(item.roleSign))
    }
    const _VenueMenuList = userVenueList.map((item, index) => ({
      label: item.name,
      key: index,
    })) ?? [];
    if (!isSuperAdmin) {
      return _VenueMenuList;
    } else {
      if (!currentVenue) {
        return _VenueMenuList
      }
      return _VenueMenuList?.concat(
        [
          {
            type: 'divider',
          },
          {
            label: '退出当前场馆',
            key: '101',
            danger: true,
          }
        ]
      )
    }
  }, [userVenueList])
  const VenueMenu = (
    <Menu className={styles.menu} onClick={handleChange} items={VenueMenuList}>
    </Menu>
  );

  return (
    <HeaderDropdown overlay={VenueMenu} placement="bottomRight">
      {
        currentVenue ? (
          <span className={classNames(styles.dropDown)}>
            当前场馆：{currentVenue?.name ?? ''}
          </span>
        ) : (
          <span className={classNames(styles.dropDown)}>
            更换场馆
          </span>
        )
      }
    </HeaderDropdown>
  );
};

export default connect(({ user }) => ({
  userVenueList: user.userVenueList,
  currentVenue: user.currentVenue
}))(SelectVenue);
